<template>
  <div class="label-selected-container" ref="labelSelect">
    <h1>{{ props.title }}</h1>
    <el-row>
      <el-col
        class="label-col"
        :span="24"
        v-for="(d, index) in data"
        :key="d.value">
        <span class="label-name">{{ d.label }}</span>
        <div class="label-list">
          <el-check-tag
            v-for="(item, subIndex) in d.list.slice(
              0,
              d.toggle ? d.list.length : showLabelLen
            )"
            :key="item.value"
            size="default"
            :checked="item.checked"
            @change="onChange($event, index, subIndex)">
            <span class="tag-content">{{ item.label }}</span>
            <span class="tag-total" v-show="d.total">{{ item.total }}</span></el-check-tag>
          <el-tag
            v-show="showLabelLen < d.list.length"
            size="default"
            @click="handleToggle(index, subIndex)">{{ d.toggle ? "收起" : "展开" }}</el-tag>
        </div>
      </el-col>
    </el-row>
  </div>
</template>
<script setup>
import {
	ref,
	onMounted,
	onBeforeUnmount,
	defineProps,
	defineEmits
} from 'vue';
const props = defineProps({
	'title': { 'type': String, 'required': false, 'default': '' },
	'dataSource': { 'type': Array, 'required': true, 'default': () => [] }
});
const emit = defineEmits(['onChange']);
const labelSelect = ref();
const showLabelLen = ref(10);
const data = ref(props.dataSource);
const onChange = (status, index, subIndex) => {
	if (!data.value[index].multiple) {
		data.value[index].list.forEach((item) => item.checked = false);
	}
	data.value[index].list[subIndex].checked = status;
	const checkedMap = {};
	data.value.forEach((d) => {
		checkedMap[d.value] = d.list.filter((i) => i.checked).map((i) => i.value);
	});
	emit('onChange', checkedMap);
};
const watchWidthChange = () => {
	const resizeObserver = new ResizeObserver((entries) => {
		for (const entry of entries) {
			const { width } = entry.contentRect;
			if (width) {
				showLabelLen.value = Math.floor(width / 84) - 2;
			}
		}
	});
	resizeObserver.observe(labelSelect.value);
};
const handleToggle = (index) => {
	data.value[index].toggle = !data.value[index].toggle;
};
onBeforeUnmount(() => {});
onMounted(() => {
	watchWidthChange();
});
</script>
<style lang="less" scoped>
.label-selected-container {
  .label-col {
    display: flex;
    .label-name {
      width: 80px;
      margin: 0 0.5rem 1rem 0;
      text-align: right;
    }
    .label-list {
      .el-check-tag {
        display: inline-flex;
        width: 60px;
        margin: 0 1rem 1rem 0;
        .tag-content {
          flex: 1;
          white-space: nowrap;
          overflow: hidden;
          text-overflow: ellipsis;
        }
        .tag-total {
          margin-left: 0.5rem;
        }
      }
    }
  }
}
</style>